package org.example.session;

import lombok.extern.slf4j.Slf4j;
import org.example.model.dto.FullUserDto;
import org.example.service.ISysUserService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.Arrays;
import java.util.concurrent.TimeUnit;

/**
 * @author weigang
 * @create 2022-11-08 14:41
 */
@Configuration
@Slf4j
public class JwtSessionConfig implements WebMvcConfigurer {
    @Value("${wg.token.interceptor.exclude:}")
    private String[] excludePath;

    @Value("${wg.token.expire.millis:}")
    private Long tokenExpireMillis = TimeUnit.DAYS.toMillis(30L);

    @Bean
    @ConditionalOnMissingBean // 声明只能配置一个这个bean的实例
    public SessionStore sessionStore(ISysUserService userService) {
        log.info(" >>>>> init  SessionStore <<<<< ");
        return new DefaultSessionStore(
                tokenExpireMillis,
                // Function接口，定义的loadUser方法
                itCode -> {
//                    List<FullUserDto> fullUsers = userService.listFullUsers(
//                            Collections.singletonList(itCode),
//                            QueryFullUserOption.getOptionExcludeLdap());
//                    if (CollUtil.isEmpty(fullUsers)) {
//                        log.info("DefaultSessionStore load token it code null, token:[{}]", itCode);
//                        throw new ServiceException(WGErrorEnum.e_1023.getCode(), WGErrorEnum.e_1023.getMsg());
//                    }
//                    FullUserDto fullUser = fullUsers.get(0);
//                    fullUser.setScopedUsersByDept(userService.getUserNamesForLoginUser(fullUser, true, false));
//                    fullUser.setScopedUsers(userService.getUserNamesForLoginUser(fullUser, true, true));
                    FullUserDto fullUser = new FullUserDto();
                    fullUser.setUserName(itCode);
                    return fullUser;
                });
    }

    @Bean
    public TokenInterceptor tokenInterceptor() {
        return new TokenInterceptor();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //注册TestInterceptor拦截器
        InterceptorRegistration registration = registry.addInterceptor(tokenInterceptor());
        log.info(" >>>>> 注册tokenInterceptor拦截器 <<<<< ");
        //所有路径都被拦截
        registration.addPathPatterns("/**");
        log.info(" >>>>> 拦截所有路径：[{}] <<<<< ","/**");
        registration.excludePathPatterns(excludePath);
        log.info(" >>>>> 将不需要拦截的路径过滤出来:[{}] <<<<< " , Arrays.toString(excludePath));
    }
}
